#pragma once
#include <iostream>
#include "Protocol.hpp"

enum
{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

// 上层业务
class Calculator
{
private:
    //业务处理
    Response CalculatorHelper(const Request& req)
    {
        Response resp(0, 0);

        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
            {
                if (req.y == 0)
                    resp.code = Div_Zero;
                else
                    resp.result = req.x / req.y;
            }
            break;
        case '%':
            {
                if (req.y == 0)
                    resp.code = Mod_Zero;
                else
                    resp.result = req.x % req.y;
            }
            break;
        default:
            resp.code = Other_Oper;
            break;
        }

        return resp;
    }
    
public:
    //"len"\n"x op y"\n"len"\n"x op y"\n"len"\n"x... 报文都是连着的，需要自己识别提取一份报文
    std::string Handler(std::string& package)
    {
        //获取正文
        std::string content;
        bool r = Decode(package, &content);                    //报文->请求->业务->响应->报文            
        if (!r)
            return "";

        //构建请求类
        Request req;
        r = req.Deserialize(content); 
        if (!r)
            return "";

        //处理请求数据得到响应
        Response resp = CalculatorHelper(req); 

        //把响应数据序列化得到正文，加工正文得到报文，返回报文
        std::string rcontent;
        resp.Serialize(&rcontent);  
        rcontent = Encode(rcontent); 
        return rcontent;
    }
};